package itbour.onetouchshow.utils.video;

import android.app.Activity;
import android.os.Handler;
import android.view.WindowManager;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.utils.HttpUtils;

import java.util.HashMap;

import itbour.onetouchshow.App;
import itbour.onetouchshow.bean.V1_4DocPreviewBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OneTouchDialogUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.TypeCastHelper;
import itbour.onetouchshow.utils.UIUtils;

import static itbour.onetouchshow.utils.video.MakeProductContrl.SignalTag.SHOW_HINT;
import static itbour.onetouchshow.utils.video.MakeProductContrl.SignalTag.SHOW_PROGRESS;

/**
 * Created by Administrator on 2018/4/2.
 */

public class MakeProductContrl {

    /**
     * 0待生成
     **/
    public static final int MAKE_PREPARING = 0;
    /**
     * 1生成中
     **/
    public static final int MAKE_MAKEING = 1;

    /**
     * 2生成失败
     **/
    public static final int MAKE_FAILE = 2;

    /**
     * 3生成成功
     **/
    public static final int MAKE_COMPLETED = 3;
    private static MakeProductContrl makeProductContrl;
    /**
     * 进度条的dialog
     */
    public OneToucDialog oneToucDialog;
    private Handler handler = UIUtils.getHandler();
    private Runnable runnable;
    private V1_4DocPreviewBean docPreviewBean;
    private V1_4DocPreviewBean.DocInfoBean docInfo;
    private V1_4DocPreviewBean.ProgressInfoBean progressInfo;
    private MakeProductListener makeOverProductListner;
    private double estimatedProgress;
    private double realProgress;
    private int generateStatus;
    private Activity activity;
    private SignalTag signalTag;
    OneTouchDialogUtils.OneTouchPorgressOver oneTouchPorgressOver = new OneTouchDialogUtils.OneTouchPorgressOver() {
        @Override
        public void onMackOver() {
            L_.e("生成完成进度走完   OneToucDialog.startQuickProgressTimer");
            newLoadDocPreview(docPreviewBean.getId());
        }
    };
    private UserMakeTag mUserMakeTag;

    public MakeProductContrl() {
    }

    public static MakeProductContrl instance() {
        if (makeProductContrl == null) {
            synchronized (MakeProductContrl.class) {
                if (makeProductContrl == null) {
                    makeProductContrl = new MakeProductContrl();
                }
            }
        }
        return makeProductContrl;
    }

    public MakeProductContrl setInitialize(MakeProductListener makeOverProductListner, Activity activity, SignalTag signal, UserMakeTag userMakeTag) {
        this.makeOverProductListner = makeOverProductListner;
        this.activity = activity;
        this.signalTag = signal;
        this.mUserMakeTag = userMakeTag;
        return this;
    }

//    /**
//     * 作品预览的两种状态
//     * 1  生成中 弹出提示框  制作提示
//     * 2  生成中弹出进度条 轮询查询
//     */
//    public MakeProductContrl(MakeProductListener makeOverProductListner, Activity activity, SignalTag signal) {
//        this.makeOverProductListner = makeOverProductListner;
//        this.activity = activity;
//        this.signalTag = signal;
//    }

    public void loadNewDocPreviewSuccess(String result) {
        //L_.e(result);
        docPreviewBean = new Gson().fromJson(result, V1_4DocPreviewBean.class);
        docInfo = docPreviewBean.getDocInfo();
        progressInfo = docPreviewBean.getProgressInfo();
        generateStatus = docInfo.getGenerateStatus();
        if (generateStatus == MAKE_FAILE) {
            if (makeOverProductListner != null) {
                makeOverProductListner.makeFaile();
            }
        } else if (generateStatus == MAKE_MAKEING || generateStatus == MAKE_PREPARING) {
            // L_.e("生成中" + oneToucDialog + "makeOverProductListner:" + makeOverProductListner);
            makeingShowDialog(progressInfo, docPreviewBean.getId());
            if (makeOverProductListner != null) {
                makeOverProductListner.makeiing(result);
            }
            //生成中
        } else {

            /**
             * 进度条没有消失就先跑完100
             */
            if (oneToucDialog != null && oneToucDialog.isShowing()) {
                // L_.e("生成完成" + oneToucDialog + "makeOverProductListner:" + makeOverProductListner);
                OneTouchDialogUtils.startProgressTimer(oneToucDialog, oneTouchPorgressOver, 100, 25);
            } else {
                L_.e("生成完成" + oneToucDialog + "makeOverProductListner:" + makeOverProductListner);
                handler.removeCallbacks(runnable);
                if (makeOverProductListner != null) {
                    makeOverProductListner.makeSuccess(result);
                }
                if (oneToucDialog != null) {
                    oneToucDialog.dismiss();
                }
            }
        }
    }

    private void makeingShowDialog(V1_4DocPreviewBean.ProgressInfoBean progressInfo, String docId) {
        showMakeDialog(progressInfo);
        if (docPreviewBean != null) {
            runnable = new Runnable() {
                @Override
                public void run() {
                    newLoadDocPreview(docId);
                }
            };
            handler.postDelayed(runnable, (long) (progressInfo.getNextInterval() * 1000));
        }
        estimatedProgress = progressInfo.getEstimatedProgress();
        realProgress = progressInfo.getProgress();
//        L_.e("当前生成进度  ：" + realProgress);
//        L_.e("下次的进度  estimatedProgress：" + estimatedProgress);
//        L_.e("下次的请求网络  getNextInterval：" + (progressInfo.getNextInterval() * 1000));
//        L_.e("isOver estimatedProgress", estimatedProgress + "");
        OneTouchDialogUtils.startProgressTimer(oneToucDialog, oneTouchPorgressOver, TypeCastHelper.toInt(estimatedProgress), 35);

    }

    /**
     * 作品预览  new
     */
    public void newLoadDocPreview(String docId) {
        //L_.e("作品预览" + docId);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("docId", docId);
        //L_.e("newLoadDocPreview App.getUserId()" + App.getUserId());
        //L_.e("newLoadDocPreview docId" + docId);
        HttpUtils.getInstance().executePost(AppConfig.REQUESTUSERDOCPRIVEWINFO_WEB_V1_1, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                T_.showCustomToast(exception);
                L_.e("newLoadDocPreview" + exception);
            }

            @Override
            protected void onSuccess(String response) {
                // loadNewDocPreviewSuccess
                if (signalTag.equals(SHOW_HINT)) {
                    showWaitloadNewDocPreviewSuccess(response);
                } else if (signalTag.equals(SHOW_PROGRESS)) {
                    loadNewDocPreviewSuccess(response);
                } else {
                    new NullPointerException("请设置类型");
                }
            }
        });
    }

    private void showMakeDialog(V1_4DocPreviewBean.ProgressInfoBean progressInfo) {
        OneToucDialog.Builder builder = new OneToucDialog.Builder(activity);
        int width = UIUtils.WHD()[0] / 3 * 2;
        if (mUserMakeTag.equals(UserMakeTag.REMOVEWATER)) {
            builder.content("正在生成高清无水印的作品" + "\n" + "大约需要(" + TypeCastHelper.toInt(Math.ceil(progressInfo.getEstimatedDuration() / 60))
                    + "分钟),请耐心等候");
        } else {
            builder.content("正在生成作品" + "\n" + "大约需要(" + TypeCastHelper.toInt(Math.ceil(progressInfo.getEstimatedDuration() / 60))
                    + "分钟),请耐心等候");
        }

        builder.neutralText("稍后查看").onNeutral(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                handler.removeCallbacks(runnable);
                if (makeOverProductListner != null) {
                    makeOverProductListner.lookLater();
                }
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                .cancelable(false).setShowDownloadProgress(true).setmWidth(width);

        if (!activity.isFinishing()) {
            try {
                if (oneToucDialog == null || !oneToucDialog.isShowing()) {
                    oneToucDialog = builder.show();
                }
            } catch (WindowManager.BadTokenException e) {
            }
        }
    }

    public void makeingShowDialog() {
        if (oneToucDialog == null || !oneToucDialog.isShowing()) {
            OneToucDialog.Builder builder = new OneToucDialog.Builder(activity);
            int width = UIUtils.WHD()[0] / 3 * 2;
            builder.content("作品生成中,请稍后查看");
            oneToucDialog = builder.neutralText("我知道了").onNeutral(new OneToucDialog.SingleButtonCallback() {
                @Override
                public void onClick(OneToucDialog dialog, DialogAction which) {
                    if (makeOverProductListner != null) {
                        makeOverProductListner.lookLater();
                    }
                }
            }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                    .cancelable(false).setmWidth(width)
                    .show();
        }
        //newLoadDocPreview(docId);

    }

    public void showWaitloadNewDocPreviewSuccess(String result) {
        docPreviewBean = new Gson().fromJson(result, V1_4DocPreviewBean.class);
        V1_4DocPreviewBean.DocInfoBean docInfo = docPreviewBean.getDocInfo();
        V1_4DocPreviewBean.ProgressInfoBean progressInfo = docPreviewBean.getProgressInfo();
        int generateStatus = docInfo.getGenerateStatus();
        //草稿
        if (generateStatus == MAKE_PREPARING) {
            if (makeOverProductListner != null) {
                makeOverProductListner.isDraft(result);
            }
            //准备在
        } else if (generateStatus == MAKE_FAILE) {
            if (makeOverProductListner != null) {
                makeOverProductListner.makeFaile();
            }
            //失败  草稿
        } else if (generateStatus == MAKE_MAKEING) {
            makeingShowDialog();
            //生成中
            if (makeOverProductListner != null) {
                makeOverProductListner.isDraft(result);
            }
        } else {
            if (makeOverProductListner != null) {
                makeOverProductListner.makeSuccess("");
            }
        }
    }

    public void oneToucDialogDismiss() {
        if (!activity.isFinishing()) {
            try {
                if (oneToucDialog != null && oneToucDialog.isShowing()) {
                    oneToucDialog.dismiss();
                }
            } catch (WindowManager.BadTokenException e) {
            }
        }
    }


    /**
     * 显示进度框和提示框
     */
    public enum SignalTag {
        SHOW_HINT, SHOW_PROGRESS
    }

    public interface MakeProductListener {


        void makeSuccess(String result);

        void makeFaile();

        void makeiing(String result);

        void lookLater();

        /**
         * 进入草稿
         */
        void isDraft(String result);
    }
}
